package spring.cloud.tasks.executor.executor.waitingExecuteTasks;

import lombok.Getter;
import lombok.Setter;

import java.util.Comparator;
import java.util.Objects;
import java.util.PriorityQueue;

/**
 * 加同步锁。往里面放数据或者往外读取数据应该是很快的。时间轮感觉不适合提前30分钟预分配的调度任务。
 */
@Setter
@Getter
public class SlidingTimeTaskBucket implements Comparable {
    public long startTime;
    public long endTime;
    public PriorityQueue taskInfoList = new PriorityQueue<TaskInfo>(16, new Comparator<TaskInfo>() {
        @Override
        public int compare(TaskInfo o1, TaskInfo o2) {
            long o1nextFireDate = o1.getNextFireDate().getTime();
            long o2nextFireDate = o2.getNextFireDate().getTime();
            if (o1nextFireDate == o2nextFireDate) {
                return 0;
            }
            return o1nextFireDate < o2nextFireDate ? -1 : 1;
        }
    });

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        SlidingTimeTaskBucket slidingTimeRangeAndTaskInfoList = (SlidingTimeTaskBucket) o;
        return startTime == slidingTimeRangeAndTaskInfoList.startTime && endTime == slidingTimeRangeAndTaskInfoList.endTime;
    }

    @Override
    public int hashCode() {
        return Objects.hash(startTime, endTime);
    }

    @Override
    public int compareTo(Object o) {
        SlidingTimeTaskBucket slidingTimeTaskBucket = (SlidingTimeTaskBucket) o;
        if (this.startTime == slidingTimeTaskBucket.startTime && this.endTime == slidingTimeTaskBucket.endTime) {
            //return 0;保证map里面只能存在一个SlidingTimeRangeAndTaskInfoList对象
            throw new IllegalArgumentException("数据范围重复了");
        }
        return this.startTime < slidingTimeTaskBucket.startTime ? -1 : 1;
    }


}
